package com.kai.steering.data.service.service.impl;

import com.kai.steering.common.web.vo.ReturnCodeExt;
import com.kai.steering.data.service.databus.enums.UsableEnum;
import com.kai.steering.data.service.entity.domainObject.CaretakerDO;
import com.kai.steering.data.service.entity.domainObject.UserDO;
import com.kai.steering.data.service.entity.dto.CaretakerQueryDTO;
import com.kai.steering.data.service.entity.po.Caretaker;
import com.kai.steering.data.service.entity.vo.CaretakerVO;
import com.kai.steering.data.service.mapper.CaretakerMapper;
import com.kai.steering.data.service.service.CaretakerService;
import com.kai.steering.common.web.service.impl.BaseServiceImpl;
import com.kai.steering.common.vo.Page;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <pre>
 * 管理员 服务实现类
 * </pre>
 *
 * @author kai
 * @since 2022-02-23
 */
@Slf4j
@Service
public class CaretakerServiceImpl extends BaseServiceImpl<CaretakerMapper, Caretaker> implements CaretakerService {

    @Autowired
    private CaretakerMapper caretakerMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveCaretaker(CaretakerDO caretakerDO) {
        /**
         * 参数检查
         */
        CaretakerDO oldCaretakerDO = getCaretakerById(caretakerDO.getCaretakerId());
        if (oldCaretakerDO != null || StringUtils.isNotEmpty(oldCaretakerDO.getCaretakerId())) {
            throw ReturnCodeExt.BUSINESS_EXCEPTION.getException(oldCaretakerDO.getCaretakerId() + "账号已存在");
        }
        /**
         * 构建对象
         */
        HttpServletRequest request =  ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        CaretakerDO own = (CaretakerDO)request.getSession().getAttribute("caretakerDO");//获取在Session储存
        caretakerDO.setFounder(own==null?own.getCaretakerId():"");
        caretakerDO.setCreationDatetime(new Date());
        Caretaker caretaker = new Caretaker(caretakerDO);
        /**
         * 保存
         */
        boolean save = super.save(caretaker);
        caretakerDO.convertCaretakerDO(caretaker);
        return save;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCaretaker(Serializable id, CaretakerDO caretakerDO) {
        /**
         * 参数检查
         */
        CaretakerDO old = getCaretakerById(id);
        if (old == null || StringUtils.isNotEmpty(old.getCaretakerId())) {
            throw ReturnCodeExt.DAO_EXCEPTION.getException(id + "id不存在");
        }
        /**
         * 服务
         */
        //数据不变
        caretakerDO.setCaretakerId(id.toString());

        /**
         * 构建对象
         */
        Caretaker caretaker = new Caretaker(caretakerDO);
        boolean b = super.updateById(caretaker);
        return b;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteCaretaker(Serializable id) {
        /**
         * 参数检查
         */
        CaretakerDO old = getCaretakerById(id);
        if (old == null || StringUtils.isNotEmpty(old.getCaretakerId())) {
            throw ReturnCodeExt.DAO_EXCEPTION.getException(id + "id不存在");
        }
        super.removeById(id);
        return true;
    }

    @Override
    public CaretakerDO getCaretakerById(Serializable id) {
        /**
         * 调用服务
         */
        Caretaker caretaker = super.getById(id);
        /**
         * 构建对象
         */
        CaretakerDO caretakerDO = new CaretakerDO(caretaker);
        return caretakerDO;
    }

    @Override
    public List<CaretakerDO> getAllCaretaker() {
        List<Caretaker> caretakerlist = caretakerMapper.selectList(new QueryWrapper<Caretaker>().eq("usable", UsableEnum.ACTIVE.getCode()));
        List<CaretakerDO> result = caretakerlist.stream()
                .map(caretaker -> {
                    CaretakerDO caretakerDO = new CaretakerDO();
                    BeanUtil.copyProperties(caretaker, caretakerDO);
                    return caretakerDO;
                })
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public Page<CaretakerVO> getCaretakerPageList(CaretakerQueryDTO caretakerQueryDTO) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page page = setPageParam(
                caretakerQueryDTO, OrderItem.desc("creation_datetime")
        );//设置排序

        QueryWrapper<Caretaker> queryWrapper = new QueryWrapper<>();
        //存在
        queryWrapper.eq("usable", UsableEnum.ACTIVE.getCode());
        //id
        if (StringUtils.isNotEmpty(caretakerQueryDTO.getCaretakerId())) {
            queryWrapper.eq("caretaker_id", caretakerQueryDTO.getCaretakerId());
        }
        //name
        if (StringUtils.isNotEmpty(caretakerQueryDTO.getCaretakerName())) {
            queryWrapper.like("caretaker_name", caretakerQueryDTO.getCaretakerName());
        }
        //地址
        if (StringUtils.isNotEmpty(caretakerQueryDTO.getAddress())) {
            queryWrapper.like("address", caretakerQueryDTO.getAddress());
        }
        //用户电话
        if (StringUtils.isNotEmpty(caretakerQueryDTO.getPhone())) {
            queryWrapper.like("phone", caretakerQueryDTO.getPhone());
        }
        //开始时间 创建
        if (caretakerQueryDTO.getCreationDateOrigin()==null){
            queryWrapper.ge("creation_datetime", caretakerQueryDTO.getCreationDateOrigin());
        }
        //结束时间 创建
        if (caretakerQueryDTO.getCreationDateTerminus()==null){
            queryWrapper.le("creation_datetime",caretakerQueryDTO.getCreationDateTerminus());
        }
        //开始时间 生日
        if (caretakerQueryDTO.getBirthdayDateOrigin()==null){
            queryWrapper.ge("birthday", caretakerQueryDTO.getBirthdayDateOrigin());
        }
        //结束时间 生日
        if (caretakerQueryDTO.getBirthdayDateTerminus()==null){
            queryWrapper.le("birthday",caretakerQueryDTO.getBirthdayDateTerminus());
        }

        //组合条件
        IPage<Caretaker> entityPage = caretakerMapper.selectPage(page, queryWrapper);
        List<CaretakerVO> result = entityPage.getRecords().stream()
                .map(caretaker -> {
                    CaretakerVO caretakerVo = new CaretakerVO();
                    BeanUtil.copyProperties(caretaker, caretakerVo);
                    return caretakerVo;
                })
                .collect(Collectors.toList());

        return Page.<CaretakerVO>builder()
                .currPage(caretakerQueryDTO.getPageNo())
                .pageSize(caretakerQueryDTO.getPageSize())
                .totalCount((int) entityPage.getTotal())
                .list(result)
                .build();
    }


    @Override
    public boolean isExists(String key, String val, Serializable id) {
        QueryWrapper<Caretaker> qw = new QueryWrapper<>();
        qw.eq(key, val);
        if (id != null) {
            qw.ne("caretaker_id", id);
        }
        int num = this.count(qw);
        return num > 0;
    }

}

